package com.oto.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Service;

import com.oto.model.AccountDO;
import com.oto.model.FlowDO;
import com.oto.util.DateUtils;
import com.oto.web.model.XmlAccount;

/**
 * @author xueqiang.mi
 * @since 2010-12-18
 */
@Service
public class AccountService extends BaseService {

	public void add(AccountDO obj) {
		if (get(obj.getName()) != null) {
			return;
		}
		Date now = DateUtils.now();
		obj.setCrtDate(now);
		obj.setModDate(now);
		save(obj);
	}

	public boolean addFrid(String name, String fridName) {
		AccountDO account = get(name);
		if (account != null) {
			account.getFriends().add(fridName);
			save(account);
			return true;
		}
		return false;
	}

	public void bind(String name, String imei) {
		AccountDO account = get(name);
		if (account != null) {
			account.setImei(imei);
			save(account);
			return;
		}
		account = new AccountDO();
		account.setName(name);
		account.setImei(imei);
		add(account);
	}

	public AccountDO get(String name) {
		return get(AccountDO.class, name);
	}

	public AccountDO getOrCreate(String name) {
		if (name == null) {
			return null;
		}
		AccountDO account = get(name);
		if (account == null) {
			account = new AccountDO();
			account.setName(name);
			add(account);
		}
		return account;
	}

	@SuppressWarnings("unchecked")
	public List<AccountDO> lattest() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(AccountDO.class);
			query.setOrdering("crtDate desc");
			query.setRange(0, 15);
			Collection<AccountDO> c = pm.detachCopyAll((Collection<AccountDO>) query.execute());
			return new ArrayList<AccountDO>(c);
		} finally {
			pm.close();
		}
	}

	/**
	 * 将一个Flow直接推送给列表中的所有用户
	 * 
	 * @param toList
	 * @param flow
	 */
	public void pushFlow(List<XmlAccount> toList, FlowDO flow) {
		PersistenceManager pm = PMF.get();
		try {
			for (XmlAccount u : toList) {
				AccountDO account = null;
				try {
					account = pm.getObjectById(AccountDO.class, u.getName());
				} catch (Exception e) {
					// Ignore
				}
				if (account == null) {
					account = new AccountDO();
					account.setName(u.getName());
					account.setType(u.getType());
					Date now = DateUtils.now();
					account.setCrtDate(now);
					account.setModDate(now);
					account.getToQueue().add(flow.getId());
					pm.makePersistent(account);
				} else {
					account.getToQueue().add(flow.getId());
				}
			}
		} finally {
			pm.close();
		}
	}

	public boolean sub(String name, long flowId) {
		AccountDO account = get(name);
		if (account != null) {
			account.getSubQueue().add(flowId);
			save(account);
			return true;
		}
		return false;
	}
}
